package com.hao.common.execption;

import com.hao.common.code.ErrorCode;
import com.hao.common.response.BaseResponse;
import com.hao.common.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/5/21 9:39
 */
@RestController
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler (BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler (RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    @ExceptionHandler (Exception.class)
    public BaseResponse<?> methodArgumentNotValidExceptionHandler(Exception e) {
        log.error("methodArgumentNotValidExceptionHandler", e);
        if (e instanceof MethodArgumentNotValidException) {
            String message = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
            log.error(message);
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, message);
        }
        if (e instanceof BindException) {
            String message = ((BindException) e).getBindingResult().getFieldError().getDefaultMessage();
            log.error(message);
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, message);
        }
        return ResultUtils.error(ErrorCode.PARAMS_ERROR,"参数错误");
    }
}
